<template>
  <div>
    <div class="data-form">
      <el-form ref="socialForm" :model="socialForm" v-show="false">
        <el-form-item>
          <el-input v-model="socialForm.providerId"></el-input>
          <el-input v-model="socialForm.state"></el-input>
          <el-input v-model="socialForm.code"></el-input>
        </el-form-item>
      </el-form>
      <el-container>
        <el-header>
        </el-header>
        <el-main>
          <el-row class="row-bg">
            <el-col :span="6" class="">
            </el-col>
            <el-col :span="12" class="border 1px;border-radius: 0px">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>你正在使用{{socialText}}登录</span>
                </div>
                <el-form ref="bindForm" :model="bindForm" class="login-form"
                         :rules="formRules"
                         label-width="40" :validate-on-rule-change="false">
                  <el-form-item prop="nickname">
                    <el-input size="small"
                              v-model="bindForm.nickname"
                              auto-complete="off"
                              placeholder="你的名字" disabled="disabled">
                      <i slot="prefix"
                         class="icon-yonghu"></i>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="mobile">
                    <el-input size="small"
                              v-model="bindForm.mobile"
                              auto-complete="off"
                              placeholder="你的手机号">
                      <i slot="prefix"
                         class="icon-yonghu"></i>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="mobileCode">
                    <el-input size="small"
                              v-model="bindForm.mobileCode"
                              auto-complete="off"
                              placeholder="你的手机验证码">
                      <i slot="prefix"
                         class="icon-yanzhengma"
                         style="margin-top:6px;"></i>
                      <template slot="append">
                        <span @click="sendSmsCode"
                              class="msg-text"
                              :class="[{display:msgKey}]">{{msgText}}</span>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-form>
                <el-button type="primary" @click="bindSocialUser" :disabled="buttonDisabled">账号绑定</el-button>
              </el-card>
            </el-col>
            <el-col :span="6" class="">
            </el-col>
          </el-row>
        </el-main>
        <el-footer>
        </el-footer>
      </el-container>
    </div>
  </div>
</template>

<script>
  import {getStore, setStore} from "@/util/store";
  import {isvalidatemobile, validatenull} from "@/util/validate";
  import {Message} from 'element-ui'
  import {bindThirdAuth} from "@/api/admin/user";

  const MSGINIT = "发送验证码",
    // MSGERROR = "验证码发送失败",
    MSGSCUCCESS = "${time}秒后重发",
    MSGTIME = 60;

  export default {
    name: 'authredirect',
    data() {
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };
      const validateCode = (rule, value, callback) => {
        if (value.length != 6) {
          callback(new Error("请输入6位数的验证码"));
        } else {
          callback();
        }
      };
      return {
        socialForm: {
          providerId: "",
          state: "",
          code: ""
        },
        bindForm: {
          nickname: "",
          mobile: "",
          mobileCode: "",
          code: ""
        },
        formRules: {
          nickname: [
            {required: true, message: "请输入你的名字", trigger: "blur"},
            {max: 8, message: "名字长度最多为8位", trigger: "blur"}
          ],
          mobile: [{required: true, trigger: "blur", validator: validatePhone}],
          mobileCode: [{required: true, trigger: "blur", validator: validateCode}]
        },
        msgText: MSGINIT,
        msgTime: MSGTIME,
        msgKey: false,
        socialText: "三方应用",
        buttonDisabled: true,
        isBindAuth: false
      }
    },
    methods: {
      existSocialUser() {
        if (validatenull(this.socialForm.providerId)) {
          Message({
            message: "不支持的第三方登陆",
            type: "error"
          });
          return;
        }
        let loading = this.$loading({
          lock: true,
          text: `玩命加载中。。。`,
          spinner: 'el-icon-loading'
        });
        this.$store.dispatch("ExistSocialUser", this.socialForm).then((data) => {
          console.log(data);
          this.buttonDisabled = false;
          if (data.data.exist) {
            //存在已有用户，直接登录
            this.handleLogin();
          } else {
            //绑定用户信息
            this.bindForm.nickname = data.data.socialName;
            this.bindForm.code = this.socialForm.code;
            Message({
              message: "请先完善信息",
              type: "info"
            });
          }
          loading.close();
        }).catch(() => {
          loading.close();
        })
      },
      bindSocialUser() {
        this.$refs.bindForm.validate(valid => {
          if (valid) {
            this.$store.dispatch("BindSocialUser", {
              oauthCode: this.socialForm.providerId,
              bindForm: this.bindForm
            }).then((data) => {
              console.log("data:{}", data);
              this.handleLogin();
            });
          }
        });

      },
      sendSmsCode() {
        const validate = isvalidatemobile(this.bindForm.mobile);
        if (validate[0]) {
          Message({
            message: validate[1],
            type: "error"
          });
          return;
        }
        if (this.msgKey) return;
        this.msgText = MSGSCUCCESS.replace("${time}", this.msgTime);
        this.msgKey = true;
        const time = setInterval(() => {
          this.msgTime--;
          this.msgText = MSGSCUCCESS.replace("${time}", this.msgTime);
          if (this.msgTime == 0) {
            this.msgTime = MSGTIME;
            this.msgText = MSGINIT;
            this.msgKey = false;
            clearInterval(time);
          }
        }, 1000);
        this.$store.dispatch("SendBindSmsCode", this.bindForm).then(() => {
          Message({
            message: "验证码发送成功",
            type: "info"
          });
        });
      },
      handleLogin() {
        window.close();
        const state = this.socialForm.state;
        const code = this.socialForm.code;
        const providerId = this.socialForm.providerId;
        const url = `${window.location.origin}/#/login?state=${state}&code=${code}&providerId=${providerId}`;
        this.$router.push({path: "/login", query: {state: state, code: code, providerId: providerId}});
        window.opener.location.href = url;
      },
      handleBind() {
        bindThirdAuth(this.socialForm.providerId, this.socialForm.code).then(response => {
          if (response.data.data) {
            this.$alert('社交账号绑定成功', '成功', {
              confirmButtonText: '确定',
              callback: action => {
                window.close()
              }
            })
          } else {
            this.$notify({
              title: '失败',
              message: '绑定失败!',
              type: 'error',
              duration: 2000
            })
          }
        });
      },
      checkState() {
        if (this.socialForm.state === 'WECHAT_LOGIN') {
          this.socialForm.state = "WECHAT";
          this.socialForm.providerId = 2;
          this.socialText = "微信";
        }
        if (this.socialForm.state === 'QQ_LOGIN') {
          this.socialForm.state = "QQ";
          this.socialForm.providerId = 3;
          this.socialText = "QQ";
        }
        if (this.socialForm.state === 'WEIBO_LOGIN') {
          this.socialForm.state = "WEIBO";
          this.socialForm.providerId = 4;
          this.socialText = "微博";
        }
        if (this.socialForm.state === 'WECHAT_BIND') {
          this.socialForm.state = "WECHAT";
          this.socialForm.providerId = 2;
          this.isBindAuth = true;
        }
        if (this.socialForm.state === 'QQ_BIND') {
          this.socialForm.state = "QQ";
          this.socialForm.providerId = 3;
          this.isBindAuth = true;
        }
        if (this.socialForm.state === 'WEIBO_BIND') {
          this.socialForm.state = "WEIBO";
          this.socialForm.providerId = 4;
          this.isBindAuth = true;
        }
      },
    },
    created() {
      const params = this.$route.query;
      this.socialForm.code = params.code;
      this.socialForm.state = params.state;

      this.checkState();

      if (this.isBindAuth) {
        //绑定第三方应用
        this.handleBind();
        return;
      } else {
        //查看是否存在当前用户
        this.existSocialUser();
      }

    }
  }
</script>


<style>
  .el-row {
    margin-bottom: 20px;
  }

  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 200px;
  }

  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
